#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
/*
    int pipe(int pipefd[2]):
        创建一个无名管道，参数[0]read文件描述符，参数[1]write文件描述符
    ssize_t read(int fd, void *buf, size_t count)：
        系统调用阻塞性，直到读到数据为止
*/
int main(void)
{

    int fd[2];//f[0]->read f[1]->write
    int r = pipe(fd);
    if (r == -1)
    {
        perror("pipe error");
        return -1;
    }

    pid_t pid = fork();
    if (pid == 0)
    {
        char buf[32] = { 0 };
        int ret = read(fd[0], buf, 32);//阻塞的读
        if (ret == -1)
        {
            perror("read pipe error");
            exit(-1);
        }
        printf("read form parent:%s\n", buf);
        exit(-1);
    }
    else if (pid > 0)
    {
        sleep(1);
        char* p = "hello son";
        int ret = write(fd[1], p, strlen(p));
        if (ret == -1)
        {
            perror("write pipe error");
            wait(NULL);
            exit(-1);
        }
        wait(NULL);//等待，防止僵尸进程
        exit(0);
    }
    else
    {
        perror("fork error");
        return -1;
    }
}